<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-05
 * Time: 17:06
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\Commodity;
use App\Models\CommodityCategory;
use App\Models\Coupon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CouponController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = $request->pageSize?$request->pageSize:20;
        $status = $request->status;
        $sql =Coupon::orderBy('createTime');
        if ($status){
            $sql->where('status',$status);
        }

        $data = $sql->paginate($pageSize)->toArray();
        $result['data'] = $data['data'];
        $result['total'] = $data['total'];
        return $this->apiResponse($result);
    }

    public function store(Request $request)
    {

        $data = $request->all();
        $validator = Validator::make($data, [
            'couponId'    =>   'integer',
            'couponPrice'  =>   'required',
            'number'  =>   'required',
            'overTime'  =>   'required',
            'startTime'  =>   'required',
            'status'  =>   'required',
            'image'  =>   'required',
            'overPrice'          =>   'required'
        ]);
        if($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        if ($data['startTime'] >= $data['overTime']){
            return $this->apiResponse('',config('errorCode.COURSE_UPDATE_FAILED'));
        }
       
        $data['couponName'] = "满".($data['overPrice']/100).'减'.($data['couponPrice']/100);
        $couponId = $data['couponId'];
        unset($data['couponId']);
        if($couponId){//修改
             $status = Coupon::where('couponId',$couponId)->update($data);
        }else{
            $data['createTime'] = date('Y-m-d H:i:s');
            $status = Coupon::create($data);
        }
        if($status){//新增成功
            return $this->apiResponse(true);
        }else{
            return $this->apiResponse('', config('errorCode.ADD_FAILED'));
        }
    }

    public function destroy($couponId)
    {

       $status = Coupon::destroy($couponId);
        if($status){//删除成功
            return $this->apiResponse(true);
        }else{
           return $this->apiResponse('', config('errorCode.NOR_FAILED'));
        }
    }

    public function update($couponId)
    {
        $coupon = Coupon::find($couponId);
        if($coupon['status'] == 1){
            $status = Coupon::where('couponId',$couponId)->update(['status'=>2]);

        }
        if($coupon['status'] == 2){
            $status = Coupon::where('couponId',$couponId)->update(['status'=>1]);

        }
        if($status){
            return $this->apiResponse(true);
        }else{
            return $this->apiResponse('', config('errorCode.PRODUCT_UPDATE_FAILED'));
        }
    }
}